package com.yjb.demo.elasticsearch.controller;

import cn.hutool.json.JSONUtil;
import com.yjb.demo.elasticsearch.common.ResponseResult;
import com.yjb.demo.elasticsearch.domain.doc.HotelDoc;
import com.yjb.demo.elasticsearch.domain.entity.Hotel;
import com.yjb.demo.elasticsearch.service.HotelService;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @description 做一些数据初始化操作，以便测试
 * @author yinjinbiao
 * @create 2024/1/11 15:47
 * @version 1.0
 */
@ApiOperation("测试前先初始化数据")
@RestController
@RequestMapping("/init")
public class InitController {

	@Resource
	private HotelService hotelService;

	@Resource
	private RestHighLevelClient client;

	/**
	 * 导入mysql数据到es
	 * @return
	 */
	@ApiOperation("测试前先初始化mysql数据到es")
	@GetMapping("importDataToEs")
	public ResponseResult initEsData() throws IOException {
		// 批量插入使用 BulkRequest
		BulkRequest request = new BulkRequest();

		List<Hotel> hotelList = hotelService.list();
		hotelList.stream().forEach(hotel -> {
			HotelDoc hotelDoc = new HotelDoc(hotel);
			request.add(new IndexRequest("hotel")
					.id(hotelDoc.getId().toString())
					.source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON));
		});
		BulkResponse bulk = client.bulk(request, RequestOptions.DEFAULT);
		return ResponseResult.ok(bulk);
	}

}
